<?php
declare(strict_types=1);

namespace app\service;

use app\model\User;
use GuzzleHttp\Client;
use think\facade\Cache;

class JutuikeService
{
    protected $pubId;
    protected $apiKey;
    protected $baseUrl = 'https://api.jutuike.com';
    
    public function __construct()
    {
        $this->pubId = env('JUTUIKE_PUB_ID', '');
        $this->apiKey = env('JUTUIKE_API_KEY', '');
    }
    
    /**
     * 获取优惠券
     */
    public function getCoupon(string $serviceType, User $user): array
    {
        try {
            // TODO: 实现聚推客API调用
            // 这里是模拟数据
            return [
                'success' => true,
                'data' => [
                    'title' => $serviceType . '优惠券',
                    'order_no' => date('YmdHis') . rand(1000, 9999),
                    'order_amount' => 100.00,
                    'merchant_commission' => 5.00,
                    'platform_commission' => 1.00
                ]
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 同步订单状态
     */
    public function syncOrderStatus(string $orderNo): array
    {
        try {
            // TODO: 实现订单状态同步
            return [
                'success' => true,
                'data' => [
                    'status' => 1,
                    'settlement_time' => date('Y-m-d H:i:s')
                ]
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取推广链接
     */
    public function getPromotionUrl(string $serviceType, User $user): array
    {
        try {
            // TODO: 实现获取推广链接
            return [
                'success' => true,
                'data' => [
                    'url' => 'https://example.com/promotion/' . $serviceType,
                    'qrcode' => 'https://example.com/qrcode/' . $serviceType
                ]
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 发送API请求
     */
    protected function request(string $path, array $params = []): array
    {
        try {
            $client = new Client();
            $params['pub_id'] = $this->pubId;
            $params['timestamp'] = time();
            $params['sign'] = $this->sign($params);
            
            $response = $client->post($this->baseUrl . $path, [
                'headers' => [
                    'apikey' => $this->apiKey
                ],
                'form_params' => $params
            ]);
            
            return json_decode($response->getBody()->getContents(), true);
            
        } catch (\Exception $e) {
            throw new \Exception('API request failed: ' . $e->getMessage());
        }
    }

    /**
     * 签名
     */
    protected function sign(array $params): string
    {
        ksort($params);
        $string = '';
        foreach ($params as $key => $value) {
            if ($key != 'sign' && !empty($value)) {
                $string .= $key . '=' . $value . '&';
            }
        }
        $string = rtrim($string, '&');
        return md5($string);
    }
} 